package com.example.futureai.config.nutz;

import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Dao;
import org.nutz.dao.util.Daos;
import org.nutz.dao.util.tables.TablesFilter;
import org.nutz.lang.Lang;
import org.nutz.resource.Scans;

import java.util.Arrays;
import java.util.List;


@Slf4j
public class NutzDatabaseInitializer {

    public NutzDatabaseInitializer(){

    }
    public NutzDatabaseInitializer(NutzDaoAutoConfigurationProperties properties, Dao dao, TablesFilter tablesFilter) {
        Daos.CHECK_COLUMN_NAME_KEYWORD = properties.getGlobal().isCheckColumnNameKeyword();
        Daos.FORCE_HUMP_COLUMN_NAME = properties.getGlobal().isForceHumpColumnName();
        Daos.FORCE_UPPER_COLUMN_NAME = properties.getGlobal().isForceUpperColumnName();
        Daos.FORCE_WRAP_COLUMN_NAME = properties.getGlobal().isForceWrapColumnName();
        Daos.DEFAULT_VARCHAR_WIDTH = properties.getGlobal().getDefaultVarcharWidth();
        boolean create = properties.getRuntime().isCreate();
        boolean migration = properties.getRuntime().isMigration();
        String[] pkgs = Lang.merge(properties.getRuntime().getBasepackage());
        if (Lang.isNotEmpty(pkgs)) {
            Arrays.stream(pkgs).forEach(pkg -> {
                List<Class<?>> classes = Scans.me().scanPackage(pkg);
                log.info("初始化数据库表结构:{}", pkg);
                if (create) {
                    Daos.createTablesInPackage(dao, pkg, false, tablesFilter);
                }
                if (migration) {
                    Daos.migration(dao, pkg, true, false, tablesFilter);
                }
            });
        }
    }
}
